<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >

      <el-form-item label="类别名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入类别名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button type="danger" @click="toggleExpandAll" plain icon="el-icon-sort">展开/折叠</el-button>
      </el-form-item>
    </el-form>
<!--    &lt;!&ndash; 操作工具栏 &ndash;&gt;-->
<!--    <el-row :gutter="10" class="mb8">-->
<!--      <el-col :span="1.5">-->
<!--        <el-button type="danger" @click="toggleExpandAll" plain icon="el-icon-sort">展开/折叠</el-button>-->
<!--      </el-col>-->
<!--    </el-row>-->
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        v-if="refreshTable"
        row-key="id"
        :default-expand-all="isExpandAll"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="类别名称" align="center" prop="name" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="状态" align="center"  prop="status" >
        <template #default="scope">
          <el-switch v-model="scope.row.status" :active-value="'0'" :inactive-value="'1'" @change="handleStatusChange(scope.row)" :disabled="scope.row.id<=2"/>
        </template>
      </el-table-column>
      <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="el-icon-edit"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['ehs:matter-category:update']"
              v-if="![1, 2].includes(scope.row.id)"
          >
            修改
          </el-button>
          <el-button
              link
              type="primary"
              icon="el-icon-plus"
              @click="openForm('create', scope.row.id)"
              v-hasPermi="['ehs:matter-category:create']"
          >
            新增
          </el-button>
<!--          <el-button  type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"-->
<!--                     v-hasPermi="['ehs:matter-category:delete']" v-if="scope.row.isFinal === '0'">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MatterCategoryForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { MatterCategoryApi, MatterCategoryVO } from '@/api/ehs/mattercategory'
import MatterCategoryForm from './MatterCategoryForm.vue'
import {handleTree } from '@/utils/tree'
import { nextTick } from 'vue'
import {CommonStatusEnum, MatterCategoryStatusEnum} from "@/utils/constants";

/** 事项类别 列表 */
defineOptions({ name: 'EhsMatterCategory' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<MatterCategoryVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  parentId: undefined,
  name: undefined,
  createTime: [],
  sort: undefined,
  remark: undefined,
  status: undefined,
})
const refreshTable = ref(true)
const isExpandAll = ref(true)

const toggleExpandAll = () =>{
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

const  handleStatusChange= async(row)=> {
  let text = row.status === MatterCategoryStatusEnum.ENABLE ? "启用" : "禁用";
  let prefixMsg = '';
  let children = row.children
  if (children !== undefined && children != null && children.length > 0) {
    prefixMsg = "该类别下有子类别，" + text + "该类别会导致该类别下的所有子类别一起被" + text + ",";
  }
  // 删除的二次确认
  await message.delConfirm(prefixMsg + '确认要"' + text + '""' + row.name + '"的类别吗?')
  try {
    await MatterCategoryApi.changeStatus(row.id, row.status);
    await getList()
    await message.success(text + "成功")
  } catch {
    row.status = row.status === MatterCategoryStatusEnum.ENABLE ? MatterCategoryStatusEnum.DISABLE : MatterCategoryStatusEnum.ENABLE;
  }

}


const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MatterCategoryApi.getMatterCategoryList(queryParams)
    list.value = handleTree(data, 'id', 'parentId');
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MatterCategoryApi.deleteMatterCategory(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await MatterCategoryApi.exportMatterCategory(queryParams)
    download.excel(data, '事项类别.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
